In computer science, a heap is a specialized tree-based data structure that satisfies the heap property: if B is a child node of A, then key(A) ≥ key(B). This implies that an element with the greatest key is always in the root node, and so such a heap is sometimes called a max-heap. (Alternatively, if the comparison is reversed, the smallest element is always in the root node, which results in a min-heap.) There is no restriction as to how many children each node has in a heap, although in practice each node has at most two. The heap is one maximally-efficient implementation of an abstract data type called a priority queue. Heaps are crucial in several efficient graph algorithms such as Dijkstra's algorithm, and in the sorting algorithm heapsort.
A heap data structure should not be confused with the heap which is a common name for dynamically allocated memory. The term was originally used only for the data structure. Some early popular languages such as LISP provided dynamic memory allocation using heap data structures, which gave the memory area its name[1].
Heaps are usually implemented in an array, and do not require pointers between elements.
The operations commonly performed with a heap are:
Contents |
The following time complexities[1] are amortized (worst-time) time complexity for entries marked by an asterisk, and regular worst case time complexities for all other entries. O(f) gives asymptotic upper bound and Θ(f) is asymptotically tight bound (see Big O notation). Function names assume a min-heap.
Operation | Binary[1] | Binomial[1] | Fibonacci[1] | Pairing[2] | Brodal[3] |
---|---|---|---|---|---|
create-heap | Θ(1) | Θ(1) | Θ(1) | ? | O(1) |
findMin | Θ(1) | O(log n) | Θ(1) | O(1)* | O(1) |
deleteMin | Θ(log n) | Θ(log n) | O(log n)* | O(log n)* | O(log n) |
insert | Θ(log n) | O(log n) | Θ(1) | O(1)* | O(1) |
decreaseKey | Θ(log n) | Θ(log n) | Θ(1)* | O(log n)* | O(1) |
merge | Θ(n) | O(log n)** | Θ(1) | O(1)* | O(1) |
(*)Amortized time
(**)Where n is the size of the larger heap
The heap data structure has many applications.
Full and almost full binary heaps may be represented in a very space-efficient way using an array alone. The first (or last) element will contain the root. The next two elements of the array contain its children. The next four contain the four children of the two child nodes, etc. Thus the children of the node at position n
would be at positions 2n
and 2n+1
in a one-based array, or 2n+1
and 2n+2
in a zero-based array. This allows moving up or down the tree by doing simple index computations. Balancing a heap is done by swapping elements which are out of order. As we can build a heap from an array without requiring extra memory (for the nodes, for example), heapsort can be used to sort an array in-place.
One more advantage of heaps over trees in some applications is that construction of heaps can be done in linear time using Tarjan's algorithm.
|
|